package net.fxug.hokuriku.chocolat.helper
{
    import mx.core.IMXMLObject;
    import mx.events.FlexEvent;

    import net.fxug.hokuriku.chocolat.dao.DatabaseManager;
    import net.fxug.hokuriku.chocolat.dao.VoteDao;
    import net.fxug.hokuriku.chocolat.events.SQLVoteEvent;
    import net.fxug.hokuriku.chocolat.events.ViewChangeEvent;
    import net.fxug.hokuriku.chocolat.model.ApplicationDataModel;
    import net.fxug.hokuriku.chocolat.service.VoteManager;
    import net.fxug.hokuriku.chocolat.view.VoteScore;

    /**
     * スコア画面のヘルパークラス
     *
     * @author shoito
     */
    public class VoteScoreHelper implements IMXMLObject
    {
        private var view:VoteScore;

        public function initialized(document:Object, id:String):void
        {
            this.view = document as VoteScore;
            this.view.addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);
        }

        private function creationCompleteHandler(event:FlexEvent):void
        {
            this.view.addEventListener(ViewChangeEvent.SHOW, view_viewChangeHandler);
        }

        private function view_viewChangeHandler(view:ViewChangeEvent):void
        {
            this.view.removeEventListener(ViewChangeEvent.SHOW, view_viewChangeHandler);

            var dbManager:DatabaseManager = DatabaseManager.getInstance();
            // TODO エラーコード
            dbManager.addEventListener(SQLVoteEvent.SELECT_VOTE_BY_SESSIONID_EVENT, dbManager_selectVoteBySessionHandler);
            dbManager.findVoteBySessionId(ApplicationDataModel.getInstance().sessionId);
        }

        private function dbManager_selectVoteBySessionHandler(sqlVoteEvent:SQLVoteEvent):void
        {
            var ary:Array = sqlVoteEvent.data as Array;

            //XXX でバッグ用コード
            if (ary == null || ary.length == 0)
            {
                view.goodScore.text = "-- へぇ";
                view.badScore.text = "--- ぶぅ";
                view.feedback.text = "コメントが見つからなかったようです。";
                return;
            }

            var heCount:int = 0;
            var boCount:int = 0;
            var index:int = ary.length;
            for (var i:int = 0; i < index; i++)
            {
                var voteDao:VoteDao = ary[i];
                voteDao.protocol ? heCount++ : boCount++;
            }

            view.goodScore.text = heCount + "へぇ";
            view.badScore.text = boCount + "ぶぅ";
            view.feedback.text = this.createCongratulationMessage(heCount, boCount);

            // VoteManagerの終了処理
            VoteManager.getInstance().close();
            // Databaseのclose処理
            DatabaseManager.getInstance().destory();
        }

        private function createCongratulationMessage(good:int, bad:int):String
        {
            return good - bad > 0 ? "あなたのスピーカーとしての腕はスティーブ・ジョブス並みと言えるでしょう。" : "たいへんよく出来ました。"
        }
    }
}